import React, { Component } from 'react';
import { TextInput, StatusBar, View, Image, Text, TouchableOpacity, BackHandler } from 'react-native';
import Colors from '../constants/Colors';
import { unitWidth, unitHeight } from '../constants/AdapterUtil';
import { IconInput } from '../components/Input';
import TextUtil from '../constants/TextUtil';
import { SubmitButton1, SubmitButton2 } from '../components/Button';
import { api_account_login } from '../constants/HttpServices';
import { postFetch } from '../constants/HttpExtension';
import { save, LoginToken, load } from '../constants/MyStorage';
import { show } from '../constants/Toast';
import NavigationService from '../constants/NavigationService';

export default class LoginScreen extends Component {

    constructor(props) {
        super(props)
        this.state = {
            mobile: '',
            password: '',
        }
    }

    componentDidMount() {
        // this.autoLogin();
        BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
    }

    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
    }

    handleBackPress = () => {
        return true;
    }

    render() {
        return (
            <View style={{ flex: 1, alignItems: 'center' }}>
                <StatusBar
                    animated={false} //指定状态栏的变化是否应以动画形式呈现。目前支持这几种样式：backgroundColor, barStyle和hidden
                    hidden={false}  //是否隐藏状态栏。
                    translucent={true}//指定状态栏是否透明。设置为true时，应用会在状态栏之下绘制（即所谓“沉浸式”——被状态栏遮住一部分）。常和带有半透明背景色的状态栏搭配使用。
                    barStyle={'dark-content'} // enum('default', 'light-content', 'dark-content')
                    backgroundColor={'rgba(0,0,0,0)'}
                />
                <Image style={{ width: 85 * unitWidth, height: 85 * unitWidth, marginTop: 100 * unitHeight }} source={require('../res/logo_a.png')} resizeMode='stretch' />
                <IconInput
                    style={{ marginTop: 70 * unitWidth }}
                    onChangeText={this.onPhoneTextChange.bind(this)}
                    IconChildren={
                        <Image style={{ width: 14 * unitWidth, height: 22 * unitHeight }} source={require('../res/ic_sj.png')} resizeMode='stretch' />
                    }
                    keyboardType='numeric'
                    maxLength={11}
                    placeholder='请输入您的手机号码'
                    value={this.state.mobile} />
                <IconInput
                    style={{ marginTop: 20 * unitWidth }}
                    onChangeText={this.onPasswordTextChange.bind(this)}
                    IconChildren={
                        <Image style={{ width: 16 * unitWidth, height: 20 * unitHeight }} source={require('../res/ic_lock.png')} resizeMode='stretch' />
                    }
                    maxLength={20}
                    secureTextEntry={true}
                    placeholder='请输入您的密码'
                    value={this.state.password} />
                {this.state.mobile != '' && this.state.password != '' ?
                    <SubmitButton1 style={{ marginTop: 32 * unitWidth }} text='登录' onPress={this.doLogin.bind(this)} />
                    :
                    <SubmitButton2 style={{ marginTop: 32 * unitWidth }} text='登录' />
                }
                <View style={{
                    width: 291 * unitWidth,
                    height: 20 * unitWidth,
                    marginTop: 16 * unitWidth,
                    flexDirection: 'row',
                    alignItems: 'center',
                    justifyContent: 'space-between'
                }}>
                    <TouchableOpacity onPress={() => { this.props.navigation.navigate('ChooseRegister') }}>
                        <Text style={{ color: Colors.color99, fontSize: 14 }}>注册帐号</Text>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => { this.props.navigation.navigate('ForgetPassword') }}>
                        <Text style={{
                            color: Colors.color99
                        }}>忘记密码?</Text>
                    </TouchableOpacity>
                </View>
            </View>
        )
    }

    onPhoneTextChange(text) {
        this.setState({
            mobile: TextUtil.getTextInput(text, 1)
        })
    }

    onPasswordTextChange(text) {
        this.setState({
            password: TextUtil.getTextInput(text, 4)
        })
    }

    toForget() {

    }

    doLogin() {
        if (this.state.mobile == '') {
            show('请输入手机号');
            return;
        } else if (this.state.password == '') {
            show('请输入密码');
            return;
        }
        let params = {
            "mobile": this.state.mobile,
            "pwd": this.state.password,
        }
        postFetch(api_account_login, params, {
            success: (response) => {
                global.token = response.result.token;
                save(LoginToken, { token: response.result.token });
                this.props.navigation.navigate('MainStack');
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }

    autoLogin() {
        load(LoginToken, {
            success: (ret) => {
                global.token = ret.token;
                NavigationService.navigate('MainStack');
            },
            fail: (err) => {
                
            }
        })
    }
}